package com.hk.utils;

import org.apache.commons.lang3.StringUtils;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * 本地日期工具类
 */
public class LocalDateUtils {

    public static final String PATTEN_DATE_SPLIT = "yyyy-MM-dd";
    public static final String PATTEN_DATE = "yyyyMMdd";

    static class DateException extends RuntimeException {
        public DateException(String message) {
            super(message);
        }

        public DateException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    /**
     * 日期格式化yyyyMMdd
     *
     * @param date
     * @return
     */
    public static Date formatDate(String date, String format) {
        if (date.length() != format.length()) {
            System.err.println("日期格式错误: " + date + " 与 " + format + " 日期格式不一致");
            return null;
        }

        try {
            LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern(format));
            Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
            return Date.from(instant);
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

    /**
     * 日期格式化yyyyMMdd
     *
     * @param date
     * @return
     */
    public static Date formatDate(String date, DateStyle dateStyle) {
        if (date == null || dateStyle == null) {
            return null;
        }
        return formatDate(date, dateStyle.getValue());
    }

    /**
     * 解析日期字符串为日期
     *
     * @param specifiedDate 待解析的日期
     * @param pattern       解析表达式
     */
    public static LocalDate parseLocalDate(String specifiedDate, String pattern) {
        if (StringUtils.isBlank(specifiedDate)) {
            throw new DateException("The date cannot be empty");
        }
        try {
            return LocalDate.parse(specifiedDate, getDateTimeFormatter(pattern));
        } catch (Exception e) {
            throw new DateException("The date is illegal");
        }
    }

    /**
     * 获取日期格式格式化实例
     *
     * @param pattern 表达式
     * @return java.time.format.DateTimeFormatter
     */
    private static DateTimeFormatter getDateTimeFormatter(String pattern) {
        pattern = StringUtils.isNotBlank(pattern) ? pattern : PATTEN_DATE_SPLIT;
        return DateTimeFormatter.ofPattern(pattern);
    }

    /**
     * 判断时间差是否小于n年
     * 例如：判断开始日期和结束日期是否在1年之内
     *
     * @param startDate
     * @param endDate
     * @param pattern
     * @param numberOfYears
     * @return
     */
    public static boolean judgeTimeDifferenceLessThanNYears(String startDate, String endDate, String pattern, int numberOfYears) {
        return judgeChronDiffLessThan(startDate, endDate, pattern, ChronoUnit.YEARS, numberOfYears);
    }

    /**
     * 小于n天，返回true
     *
     * @param startDate
     * @param endDate
     * @param pattern
     * @param numberOfDays
     * @return
     */
    public static boolean judgeDaysDiffLessThanNDays(String startDate, String endDate, String pattern, int numberOfDays) {
        return judgeChronDiffLessThan(startDate, endDate, pattern, ChronoUnit.DAYS, numberOfDays);
    }

    public static boolean judgeWeeksDiffLessThanNWeeks(String startDate, String endDate, String pattern, int numberOfDays) {
        return judgeChronDiffLessThan(startDate, endDate, pattern, ChronoUnit.WEEKS, numberOfDays);
    }

    /**
     * 判断时间差是否在预期范围内
     *
     * @param startDate
     * @param endDate
     * @param pattern
     * @param unit
     * @param numberOfUnit
     * @return
     */
    public static boolean judgeChronDiffLessThan(String startDate, String endDate, String pattern, ChronoUnit unit, int numberOfUnit) {
        LocalDate startLocalDate = parseLocalDate(startDate, pattern);
        LocalDate endLocalDate = parseLocalDate(endDate, pattern);
        if (!(startLocalDate.isBefore(endLocalDate) || startLocalDate.isEqual(endLocalDate))) {
            throw new DateException("The start date must be earlier than or equal to the end date");
        }
        LocalDate newDate = startLocalDate.plus(numberOfUnit, unit);
        /**
         * 新日期与结束日期相同 或 新日期仍然大于结束日期：开始日期和结束日期在预期范围差内
         */
        if (newDate.isAfter(endLocalDate)) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        testDiffYears();
        testDiffDays();
        testDiffWeeks();
    }

    private static void testDiffYears() {
        String startDate = "2021-01-01";
        String endDate = "2022-01-01";
        int numberOfYears = 1;
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s年内结果：%s", startDate, endDate, numberOfYears,
                judgeTimeDifferenceLessThanNYears(startDate, endDate, PATTEN_DATE_SPLIT, numberOfYears)));

        startDate = "2000-01-01";
        endDate = "2000-12-31";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s年内结果：%s", startDate, endDate, numberOfYears,
                judgeTimeDifferenceLessThanNYears(startDate, endDate, PATTEN_DATE_SPLIT, numberOfYears)));

        startDate = "2000-01-02";
        endDate = "2000-12-31";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s年内结果：%s", startDate, endDate, numberOfYears,
                judgeTimeDifferenceLessThanNYears(startDate, endDate, PATTEN_DATE_SPLIT, numberOfYears)));

        startDate = "2000-01-01";
        endDate = "2001-01-01";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s年内结果：%s", startDate, endDate, numberOfYears,
                judgeTimeDifferenceLessThanNYears(startDate, endDate, PATTEN_DATE_SPLIT, numberOfYears)));

        startDate = "2000-01-01";
        endDate = "2000-12-29";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s年内结果：%s", startDate, endDate, numberOfYears,
                judgeTimeDifferenceLessThanNYears(startDate, endDate, PATTEN_DATE_SPLIT, numberOfYears)));
    }

    private static void testDiffDays() {
        String startDate = "2021-01-01";
        String endDate = "2022-01-01";
        int numberOfYears = 365;
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s天内结果：%s", startDate, endDate, numberOfYears,
                judgeDaysDiffLessThanNDays(startDate, endDate, PATTEN_DATE_SPLIT, numberOfYears)));

        startDate = "2000-01-01";
        endDate = "2000-12-31";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s天内结果：%s", startDate, endDate, numberOfYears,
                judgeDaysDiffLessThanNDays(startDate, endDate, PATTEN_DATE_SPLIT, numberOfYears)));

        startDate = "2000-01-02";
        endDate = "2000-12-31";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s天内结果：%s", startDate, endDate, numberOfYears,
                judgeDaysDiffLessThanNDays(startDate, endDate, PATTEN_DATE_SPLIT, numberOfYears)));

        startDate = "2000-01-01";
        endDate = "2001-01-01";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s天内结果：%s", startDate, endDate, numberOfYears,
                judgeDaysDiffLessThanNDays(startDate, endDate, PATTEN_DATE_SPLIT, numberOfYears)));

        startDate = "2000-01-01";
        endDate = "2000-12-29";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s天内结果：%s", startDate, endDate, numberOfYears,
                judgeDaysDiffLessThanNDays(startDate, endDate, PATTEN_DATE_SPLIT, numberOfYears)));
    }

    private static void testDiffWeeks() {
        String startDate = "2021-01-01";
        String endDate = "2022-01-01";
        int numberOfWeeks = 52;
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s周内结果：%s", startDate, endDate, numberOfWeeks,
                judgeWeeksDiffLessThanNWeeks(startDate, endDate, PATTEN_DATE_SPLIT, numberOfWeeks)));

        startDate = "2000-01-01";
        endDate = "2000-12-31";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s周内结果：%s", startDate, endDate, numberOfWeeks,
                judgeWeeksDiffLessThanNWeeks(startDate, endDate, PATTEN_DATE_SPLIT, numberOfWeeks)));

        startDate = "2000-01-02";
        endDate = "2000-12-31";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s周内结果：%s", startDate, endDate, numberOfWeeks,
                judgeWeeksDiffLessThanNWeeks(startDate, endDate, PATTEN_DATE_SPLIT, numberOfWeeks)));

        startDate = "2000-01-01";
        endDate = "2001-01-01";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s周内结果：%s", startDate, endDate, numberOfWeeks,
                judgeWeeksDiffLessThanNWeeks(startDate, endDate, PATTEN_DATE_SPLIT, numberOfWeeks)));

        startDate = "2000-01-01";
        endDate = "2000-12-29";
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s周内结果：%s", startDate, endDate, numberOfWeeks,
                judgeWeeksDiffLessThanNWeeks(startDate, endDate, PATTEN_DATE_SPLIT, numberOfWeeks)));

        startDate = "2021-12-01";
        endDate = "2021-12-29";
        numberOfWeeks = 4;
        System.out.println(String.format("开始日期：%s，结束日期：%s，相差范围在%s周内结果：%s", startDate, endDate, numberOfWeeks,
                judgeWeeksDiffLessThanNWeeks(startDate, endDate, PATTEN_DATE_SPLIT, numberOfWeeks)));
    }

}